%%%-------------------------------------------------------------------
%%% File    : p20.erl
%%% Author  : Plamen Dragozov <plamen at dragozov.com>
%%% Description : 
%%% n! means n × (n − 1) × ... × 3 × 2 × 1
%%% Find the sum of the digits in the number 100!
%%% 
%%% Created :  5 Dec 2008
%%%-------------------------------------------------------------------
-module(p20).

%% API
-compile(export_all).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: solution(N) -> int()
%% Description: Returns the sum of the digits of N!
%%--------------------------------------------------------------------
solution(N) ->
    lists:sum(digits_factorial(N)).

%%====================================================================
%% Internal functions
%%====================================================================

%Returns a list of the digits of N! 
digits_factorial(N) ->
    digits_factorial(2, N, [1]).

digits_factorial(N, N, Acc)-> 
    digits_multiply(N, Acc);
digits_factorial(I, N, Acc)->
    digits_factorial(I + 1, N, digits_multiply(I, Acc)).

%Return a list of the digits of the result of the multiplication of N
%and the number in Digits
digits_multiply(N, Digits) ->
    digits_multiply(N, lists:reverse(Digits), 0, []).

digits_multiply(_, [], 0, Acc) -> Acc;
digits_multiply(N, [], Rem, Acc) ->
    digits_multiply(N, [], Rem div 10, [Rem rem 10|Acc]);
digits_multiply(N, [DigitsH| DigitsT], Rem, Acc) ->
    Mul = N*DigitsH + Rem,
    digits_multiply(N, DigitsT, Mul div 10, [Mul rem 10 | Acc]).


